<template>
	<view class="knowledge-detail-page">
		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<up-loading-icon mode="circle" size="40"></up-loading-icon>
		</view>

		<!-- 详情内容 -->
		<view v-else class="detail-container">
			<!-- 头部信息 -->
			<view class="header">
				<view class="category-tag">
					<up-icon :name="knowledge.icon" size="20" :color="knowledge.color"></up-icon>
					<text class="category-text">{{ knowledge.category }}</text>
				</view>
				<text class="title">{{ knowledge.title }}</text>
				<view class="meta-info">
					<view class="meta-item">
						<up-icon name="eye" size="14" color="#999"></up-icon>
						<text class="meta-text">{{ knowledge.views }}次浏览</text>
					</view>
					<view class="meta-item">
						<up-icon name="clock" size="14" color="#999"></up-icon>
						<text class="meta-text">{{ knowledge.publishTime }}</text>
					</view>
				</view>
			</view>

			<!-- 作者信息 -->
			<view class="author-section">
				<view class="author-info">
					<up-avatar :src="knowledge.authorAvatar" size="40"></up-avatar>
					<view class="author-detail">
						<text class="author-name">{{ knowledge.authorName }}</text>
						<text class="author-desc">{{ knowledge.authorDesc }}</text>
					</view>
				</view>
				<up-button 
					size="small" 
					:type="isFollowed ? 'default' : 'primary'" 
					@click="handleFollow"
				>
					{{ isFollowed ? '已关注' : '关注' }}
				</up-button>
			</view>

			<!-- 正文内容 -->
			<view class="content">
				<rich-text :nodes="knowledge.content"></rich-text>
			</view>

			<!-- 标签 -->
			<view class="tags" v-if="knowledge.tags && knowledge.tags.length">
				<up-tag 
					v-for="tag in knowledge.tags" 
					:key="tag" 
					:text="tag" 
					plain 
					size="mini" 
					type="primary"
					class="tag-item"
				/>
			</view>

			<!-- 底部操作栏 -->
			<view class="footer-actions">
				<view class="action-item" @click="handleLike">
					<up-icon 
						:name="isLiked ? 'thumb-up-fill' : 'thumb-up'" 
						size="20" 
						:color="isLiked ? '#5B8CFF' : '#666'"
					></up-icon>
					<text :class="['action-text', { active: isLiked }]">{{ knowledge.likes }}</text>
				</view>
				<view class="action-item" @click="handleCollect">
					<up-icon 
						:name="isCollected ? 'star-fill' : 'star'" 
						size="20" 
						:color="isCollected ? '#FFA500' : '#666'"
					></up-icon>
					<text :class="['action-text', { active: isCollected }]">
						{{ isCollected ? '已收藏' : '收藏' }}
					</text>
				</view>
				<view class="action-item" @click="handleShare">
					<up-icon name="share" size="20" color="#666"></up-icon>
					<text class="action-text">分享</text>
				</view>
			</view>

			<!-- 相关推荐 -->
			<view class="related-section" v-if="relatedList.length">
				<view class="section-title">相关推荐</view>
				<view class="related-list">
					<view 
						class="related-item" 
						v-for="item in relatedList" 
						:key="item.id"
						@click="handleRelatedClick(item.id)"
					>
						<text class="related-title">{{ item.title }}</text>
						<view class="related-meta">
							<text class="related-meta-text">{{ item.views }}浏览</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

// 知识详情数据
const knowledge = ref({
	id: 0,
	title: '',
	category: '',
	icon: '',
	color: '',
	content: '',
	views: 0,
	likes: 0,
	publishTime: '',
	authorName: '',
	authorAvatar: '',
	authorDesc: '',
	tags: []
});

// 加载状态
const loading = ref(true);

// 交互状态
const isFollowed = ref(false);
const isLiked = ref(false);
const isCollected = ref(false);

// 相关推荐列表
const relatedList = ref([]);

// 页面加载时获取知识ID
onLoad((options) => {
	if (options.id) {
		loadKnowledgeDetail(options.id);
	}
});

// 加载知识详情
const loadKnowledgeDetail = (id) => {
	loading.value = true;
	
	// 模拟数据
	setTimeout(() => {
		// 根据ID获取对应的知识详情（这里使用模拟数据）
		const mockData = {
			1: {
				id: 1,
				category: '编程',
				icon: 'code',
				color: '#5B8CFF',
				title: 'JavaScript异步编程详解',
				content: `
					<h2>什么是异步编程？</h2>
					<p>异步编程是指程序在等待某个操作完成时，不会阻塞其他操作的执行。在JavaScript中，异步编程非常重要，因为很多操作（如网络请求、文件读取等）都需要时间来完成。</p>
					
					<h2>Promise的使用</h2>
					<p>Promise是JavaScript中处理异步操作的一种方式。它代表一个异步操作的最终完成（或失败）及其结果值。</p>
					<pre><code>const promise = new Promise((resolve, reject) => {
  // 异步操作
  setTimeout(() => {
    resolve('操作成功');
  }, 1000);
});</code></pre>
					
					<h2>async/await语法</h2>
					<p>async/await是基于Promise的语法糖，让异步代码看起来更像同步代码，提高了可读性。</p>
					<pre><code>async function fetchData() {
  try {
    const response = await fetch('api/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('请求失败:', error);
  }
}</code></pre>
					
					<h2>最佳实践</h2>
					<ul>
						<li>优先使用async/await而不是原始的Promise链</li>
						<li>始终处理错误情况</li>
						<li>避免在循环中使用await</li>
						<li>合理使用Promise.all()并发执行多个异步操作</li>
					</ul>
				`,
				views: 1280,
				likes: 156,
				publishTime: '2024-10-20',
				authorName: '前端小张',
				authorAvatar: 'https://picsum.photos/100',
				authorDesc: '资深前端工程师，热爱分享技术',
				tags: ['JavaScript', 'Promise', 'async/await', '异步编程']
			},
			2: {
				id: 2,
				category: '编程',
				icon: 'code',
				color: '#5B8CFF',
				title: 'Vue3组合式API快速入门',
				content: `
					<h2>Vue3组合式API简介</h2>
					<p>Vue3引入了组合式API（Composition API），这是一种新的代码组织方式，让我们能够更好地复用逻辑和组织代码。</p>
					
					<h2>setup函数</h2>
					<p>setup是组合式API的入口点，在这里我们可以定义响应式数据、计算属性、方法等。</p>
					<pre><code>import { ref, computed } from 'vue';

export default {
  setup() {
    const count = ref(0);
    const double = computed(() => count.value * 2);
    
    function increment() {
      count.value++;
    }
    
    return { count, double, increment };
  }
}</code></pre>
					
					<h2>响应式基础</h2>
					<p>Vue3提供了ref和reactive两种方式创建响应式数据。</p>
					<ul>
						<li>ref：用于基本类型数据</li>
						<li>reactive：用于对象类型数据</li>
					</ul>
				`,
				views: 956,
				likes: 123,
				publishTime: '2024-10-18',
				authorName: 'Vue开发者',
				authorAvatar: 'https://picsum.photos/101',
				authorDesc: 'Vue框架爱好者',
				tags: ['Vue3', 'Composition API', '前端开发']
			}
			// 可以继续添加更多模拟数据
		};

		knowledge.value = mockData[id] || {
			id: parseInt(id),
			category: '未知',
			icon: 'info-circle',
			color: '#999',
			title: '知识内容',
			content: '<p>暂无详细内容</p>',
			views: 0,
			likes: 0,
			publishTime: '2024-10-30',
			authorName: '匿名用户',
			authorAvatar: 'https://picsum.photos/102',
			authorDesc: '暂无简介',
			tags: []
		};

		// 加载相关推荐
		relatedList.value = [
			{ id: 3, title: '高效记忆法：如何快速背单词', views: 2341 },
			{ id: 4, title: '大学生活必备APP推荐', views: 1567 },
			{ id: 5, title: '数据结构与算法学习路线', views: 3421 }
		].filter(item => item.id !== parseInt(id));

		loading.value = false;
	}, 500);
};

// 关注
const handleFollow = () => {
	isFollowed.value = !isFollowed.value;
	uni.showToast({
		title: isFollowed.value ? '关注成功' : '已取消关注',
		icon: 'none'
	});
};

// 点赞
const handleLike = () => {
	isLiked.value = !isLiked.value;
	knowledge.value.likes += isLiked.value ? 1 : -1;
	uni.showToast({
		title: isLiked.value ? '点赞成功' : '已取消点赞',
		icon: 'none'
	});
};

// 收藏
const handleCollect = () => {
	isCollected.value = !isCollected.value;
	uni.showToast({
		title: isCollected.value ? '收藏成功' : '已取消收藏',
		icon: 'none'
	});
};

// 分享
const handleShare = () => {
	uni.showToast({
		title: '分享功能开发中',
		icon: 'none'
	});
};

// 点击相关推荐
const handleRelatedClick = (id) => {
	// 重新加载页面数据
	loadKnowledgeDetail(id);
	// 滚动到顶部
	uni.pageScrollTo({
		scrollTop: 0,
		duration: 300
	});
};
</script>

<style lang="scss" scoped>
@import '../../styles/variables.scss';
@import '../../styles/mixins.scss';

.knowledge-detail-page {
	min-height: 100vh;
	background: $bg-page;

	.loading-container {
		@include flex-center;
		min-height: 100vh;
	}

	.detail-container {
		padding-bottom: 120rpx;

		// 头部信息
		.header {
			background: $bg-card;
			padding: $spacing-lg;
			margin-bottom: $spacing-base;

			.category-tag {
				display: flex;
				align-items: center;
				gap: $spacing-xs;
				margin-bottom: $spacing-base;

				.category-text {
					font-size: $font-sm;
					color: $text-secondary;
				}
			}

			.title {
				display: block;
				font-size: $font-xl;
				font-weight: $font-bold;
				color: $text-primary;
				line-height: $line-height-relaxed;
				margin-bottom: $spacing-base;
			}

			.meta-info {
				display: flex;
				gap: $spacing-lg;

				.meta-item {
					display: flex;
					align-items: center;
					gap: $spacing-xs;

					.meta-text {
						font-size: $font-xs;
						color: $text-tertiary;
					}
				}
			}
		}

		// 作者信息
		.author-section {
			background: $bg-card;
			padding: $spacing-lg;
			margin-bottom: $spacing-base;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.author-info {
				display: flex;
				gap: $spacing-base;

				.author-detail {
					display: flex;
					flex-direction: column;
					justify-content: center;

					.author-name {
						font-size: $font-base;
						font-weight: $font-medium;
						color: $text-primary;
						margin-bottom: $spacing-xs;
					}

					.author-desc {
						font-size: $font-xs;
						color: $text-tertiary;
					}
				}
			}
		}

		// 正文内容
		.content {
			background: $bg-card;
			padding: $spacing-lg;
			margin-bottom: $spacing-base;

			/* #ifdef H5 */
			// H5 端可以使用 :deep() 选择器控制 rich-text 内容样式
			:deep(.rich-text-h2) {
				font-size: $font-lg;
				font-weight: $font-semibold;
				color: $text-primary;
				margin: $spacing-lg 0 $spacing-base 0;

				&:first-child {
					margin-top: 0;
				}
			}
			
			:deep(.rich-text-p) {
				font-size: $font-base;
				color: $text-secondary;
				line-height: $line-height-relaxed;
				margin-bottom: $spacing-base;
			}

			:deep(.rich-text-pre) {
				background: $bg-page;
				padding: $spacing-base;
				border-radius: $radius-base;
				margin: $spacing-base 0;
				overflow-x: auto;

				.rich-text-code {
					font-size: $font-sm;
					color: $text-primary;
					font-family: 'Courier New', monospace;
				}
			}

			:deep(.rich-text-ul) {
				margin: $spacing-base 0;
				padding-left: $spacing-xl;

				.rich-text-li {
					font-size: $font-base;
					color: $text-secondary;
					line-height: $line-height-relaxed;
					margin-bottom: $spacing-sm;
				}
			}
			/* #endif */
		}

		// 标签
		.tags {
			background: $bg-card;
			padding: $spacing-lg;
			margin-bottom: $spacing-base;
			display: flex;
			flex-wrap: wrap;
			gap: $spacing-sm;

			.tag-item {
				margin: 0;
			}
		}

		// 底部操作栏
		.footer-actions {
			background: $bg-card;
			padding: $spacing-lg;
			margin-bottom: $spacing-base;
			display: flex;
			justify-content: space-around;
			align-items: center;

			.action-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				gap: $spacing-xs;
				cursor: pointer;

				.action-text {
					font-size: $font-xs;
					color: $text-tertiary;

					&.active {
						color: $primary-color;
					}
				}
			}
		}

		// 相关推荐
		.related-section {
			background: $bg-card;
			padding: $spacing-lg;

			.section-title {
				font-size: $font-lg;
				font-weight: $font-semibold;
				color: $text-primary;
				margin-bottom: $spacing-base;
			}

			.related-list {
				.related-item {
					padding: $spacing-base 0;
					border-bottom: 1px solid $border-light;

					&:last-child {
						border-bottom: none;
					}

					.related-title {
						display: block;
						font-size: $font-base;
						color: $text-primary;
						margin-bottom: $spacing-xs;
						@include ellipsis(2);
					}

					.related-meta {
						.related-meta-text {
							font-size: $font-xs;
							color: $text-tertiary;
						}
					}
				}
			}
		}
	}
}
</style>

